package com.changhong.wlyspectrum.NewDesign;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.changhong.wlyspectrum.MainTestActivity.InfoInputActivity;
import com.changhong.wlyspectrum.MainTestActivity.MainTestActivity;
import com.changhong.wlyspectrum.MainTestActivity.TestRecordActivity;
import com.changhong.wlyspectrum.NetWork.HttpMethods;
import com.changhong.wlyspectrum.R;
import com.changhong.wlyspectrum.utils.Attributes;
import com.changhong.wlyspectrum.utils.MyCollectionData;
import com.changhong.wlyspectrum.utils.MyConfig;
import com.google.gson.Gson;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.internal.spdy.FrameReader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.io.IOException;
import java.util.Collection;
import java.util.List;

/**
 * Created by Mr_tao
 * on 2017/3/21.
 */
public class HomeActivity extends Activity{
    private static final String TAG = "HomeActivity";
    private ImageView mBackImv;
    private TextView mAddImv;
    private String user_id;
    private String token;
    private ListView mListView;
    private CollectionAdapter mAdapter;
    private JSONArray jsonArray = null;
    private int ClickPosition = -1;

    private String yphone;
    private String[]  all_id;
    private String[] all_icon;

    //针对铁骑力士用户，只显示5个条目，id 分别是1、39-41.
    private static  final  String tqphone = "13990127580";
    private static  final  int tqnum = 5;

    //private int show_id[] = new int[]{1,3,4,10,11,40,43,44,46}; //显示项目对于的id号

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_layout);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar_home_layout);

        InitData();
        InitUi();
        GetCollection();
    }

    private void InitData() {
        SharedPreferences mypref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        user_id = mypref.getString("user_id", "default");
        token = mypref.getString("token", "default");
        yphone = mypref.getString("phone","default");
        Log.e(TAG,"yphone:"+yphone);
        all_id = getResources().getStringArray(R.array.id);
        all_icon = getResources().getStringArray(R.array.icon_name);
    }

    private void InitUi() {
        /*mBackImv = (ImageView) findViewById(R.id.home2login);
        mBackImv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });*/

        mAddImv = (TextView) findViewById(R.id.new_btn);
        mAddImv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // mAddImv.setTextColor(Color.rgb(109,109,109));
                Intent intent = new Intent(HomeActivity.this, CollectionActivity.class);
                startActivity(intent);
            }
        });

        mListView = (ListView) findViewById(R.id.home_list);
        mAdapter = new CollectionAdapter();
       /* mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                //ToDo OnClickListener
                ViewHolder viewHolder = (ViewHolder) view.getTag();
                String id = viewHolder.id;
                Log.e(TAG, viewHolder.id);
                if (id.compareTo("1") == 0) {
                    Intent intent = new Intent(HomeActivity.this, MainTestActivity.class);
                    //Intent intent = new Intent(HomeActivity.this, TestRecordActivity.class);
                    intent.putExtra("collectionId", id);
                    intent.putExtra("title_name", getString(R.string.tieqishi));
                    intent.putExtra("btn_1", getString(R.string.protein_analyse));
                    intent.putExtra("btn_2", getString(R.string.protein_model));
                    startActivity(intent);
                } else if (id.compareTo("2") == 0) {
                    Intent intent = new Intent(HomeActivity.this, InfoInputActivity.class);
                    //Intent intent = new Intent(HomeActivity.this, TestRecordActivity.class);
                    intent.putExtra("collectionId", id);
                    intent.putExtra("title_name", getString(R.string.wuliangye));
                    intent.putExtra("btn_1", getString(R.string.alcohol_analyse));
                    intent.putExtra("btn_2", getString(R.string.alcohol_model));
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(HomeActivity.this, MainTestActivity.class);
                    intent.putExtra("collectionId", id);
                    intent.putExtra("title_name", getString(R.string.common_title));
                    intent.putExtra("btn_1", getString(R.string.common_analyse));
                    intent.putExtra("btn_2", getString(R.string.common_model));
                    startActivity(intent);
                }
            }
        });*/
    }

    public Handler CollectionHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    mListView.setAdapter(mAdapter);
                    break;
                case 1:
                    Toast.makeText(getApplicationContext(), getString(R.string.no_collection), Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                   /* jsonArray=getJsonArray();*/
                    mAdapter.notifyDataSetChanged();
                    Toast.makeText(getApplicationContext(), getString(R.string.modify_success), Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    Toast.makeText(getApplicationContext(), getString(R.string.modify_fail), Toast.LENGTH_SHORT).show();
                    break;
                case 99:
                    Toast.makeText(getApplicationContext(), getString(R.string.network_error), Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };

    class CollectionAdapter extends BaseAdapter {

        private int currentItem = -1;

        @Override
        public int getCount() {
            Log.e(TAG,"jsonArray.length(): "+jsonArray.length());
            return jsonArray.length();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup viewGroup) {
            ViewHolder holder = null;
            String collectionId = null;
            String name = null;
            String des = null;
            String ctime = null;
            String ltime = null;
            if (convertView == null) {
                convertView = View.inflate(getApplicationContext(), R.layout.activity_home_list_item, null);
                ViewHolder viewHolder = new ViewHolder(convertView);
                convertView.setTag(viewHolder);
            }

            holder = (ViewHolder) convertView.getTag();


            try {
                Log.e(TAG,"wydong createUserId getView---");
                JSONObject colleciton = (JSONObject) jsonArray.get(position);
                collectionId = colleciton.getString("collectionId");
                name = colleciton.getString("name");
                des = colleciton.getString("description");
                ctime = colleciton.getString("createdTime");
                ltime = colleciton.getString("lastModifiedTime");

                //String createUserId = colleciton.getString("createUserId");
                //Log.e(TAG,"wydong createUserId:"+createUserId);
                /*if(position == 1){
                    String attri = colleciton.getString("attributes");
                    Log.e(TAG,attri);
                    //Gson gson = new Gson();
                    //List<Attributes> attributesList = gson.fromJson(collectionId.get)
                }*/
            } catch (JSONException e) {
                Log.e(TAG,"wydong createUserId getView-------------------");
                e.printStackTrace();
            }

            holder.nameTv.setText(name);
            holder.id = collectionId;
            holder.idTv.setText("ID:" + collectionId);
            holder.desTv.setText(getResources().getString(R.string.description)+ des);
            //holder.ctimeTv.setText("创建时间:   " + MyConfig.stampToDate(ctime));
            holder.ltimeTv.setText(getResources().getString(R.string.modify_time) + MyConfig.stampToDate(ltime));
            //convertView.setTag(Integer.parseInt(collectionId));

            holder.name = name;
            holder.description = des;
            //根据collectionId 多的对应的索引，进而获得指定的icon名称，如果arrary中没有列出，默认索引为0，默认icon名称为default_icon
            String icon_name = all_icon[getIconIndex(collectionId)];
            int icon_res_id = getResources().getIdentifier(icon_name,"mipmap",getPackageName());
            holder.icon.setImageDrawable(getResources().getDrawable(icon_res_id));
            holder.detect.setTag(holder);
            holder.detect.setOnClickListener(listener);
           /* if(ClickPosition==position){
                if(holder.imageButton.isSelected()){
                    holder.imageButton.setSelected(false);
                    holder.hide.setVisibility(View.GONE);
                    ClickPosition=-1;
                }else{
                    holder.imageButton.setSelected(true);
                    holder.hide.setVisibility(View.VISIBLE);
                }
            }else{
                holder.hide.setVisibility(View.GONE);
                holder.imageButton.setSelected(false);
            }

            holder.imageButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ClickPosition=position;
                    notifyDataSetChanged();
                }
            });*/

  /*          holder.imageButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.e("wydong", "isSelected:" + holder.imageButton.isSelected());
                    if (holder.imageButton.isSelected()) {
                        holder.hide.setVisibility(View.GONE);
                        holder.imageButton.setSelected(false);
                    } else {
                        holder.hide.setVisibility(View.VISIBLE);
                        holder.imageButton.setSelected(true);
                    }

                }
            });*/


           // Button btnCollection = (Button) convertView.findViewById(R.id.btn_collection);
            //Button btnAttribute = (Button) convertView.findViewById(R.id.btn_attribute);
           // btnCollection.setTag(holder);
           // btnAttribute.setTag(holder);
            //btnCollection.setOnClickListener(listener);
            //btnAttribute.setOnClickListener(listener);

            return convertView;
        }

        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewHolder holder = (ViewHolder) v.getTag();
                switch (v.getId()) {
                    case R.id.detect:
                        String id = holder.id;
                        Log.e(TAG, holder.id);
                        if (id.compareTo("1") == 0) {
                            Intent intent = new Intent(HomeActivity.this, MainTestActivity.class);
                            //Intent intent = new Intent(HomeActivity.this, TestRecordActivity.class);
                            intent.putExtra("collectionId", id);
                            intent.putExtra("title_name", getString(R.string.tieqishi));
                            intent.putExtra("btn_1", getString(R.string.protein_analyse));
                            intent.putExtra("btn_2", getString(R.string.protein_model));
                            startActivity(intent);
                        } else if (id.compareTo("2") == 0) {
                            Intent intent = new Intent(HomeActivity.this, InfoInputActivity.class);
                            //Intent intent = new Intent(HomeActivity.this, TestRecordActivity.class);
                            intent.putExtra("collectionId", id);
                            intent.putExtra("title_name", getString(R.string.wuliangye));
                            intent.putExtra("btn_1", getString(R.string.alcohol_analyse));
                            intent.putExtra("btn_2", getString(R.string.alcohol_model));
                            startActivity(intent);
                        } else {
                            Intent intent = new Intent(HomeActivity.this, MainTestActivity.class);
                            intent.putExtra("collectionId", id);
                            intent.putExtra("title_name", getString(R.string.common_title));
                            intent.putExtra("btn_1", getString(R.string.common_analyse));
                            intent.putExtra("btn_2", getString(R.string.common_model));
                            startActivity(intent);
                        }
                        break;
                    /*case R.id.btn_collection:
                        AlertDialog.Builder dialog = new AlertDialog.Builder(HomeActivity.this);
                        dialog.setTitle("修改集合信息");
                        View dialogView = LayoutInflater.from(HomeActivity.this).inflate(R.layout.dialog_modify_collection_layout, null);
                        final EditText tv_name = (EditText) dialogView.findViewById(R.id.tv_name);
                        final EditText tv_description = (EditText) dialogView.findViewById(R.id.tv_description);
                        tv_name.setHint(holder.name);
                        tv_description.setHint(holder.description);
                        dialog.setView(dialogView);
                        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                try {
                                    JSONObject jsonObject = new JSONObject();
                                    jsonObject.put("collectionId", holder.id);
                                    jsonObject.put("name", tv_name.getText().toString());
                                    jsonObject.put("description", tv_description.getText().toString());
                                    modifyCollectionInfo(jsonObject.toString());
                                    Toast.makeText(HomeActivity.this, "数据保存成功:" + jsonObject.toString(), Toast.LENGTH_SHORT).show();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //Toast.makeText(HomeActivity.this, "数据保存失败", Toast.LENGTH_SHORT).show();
                            }
                        });
                        dialog.show();
                        Log.i(TAG, "Modify collection " + holder.nameTv.getText());
                        break;*/
                    /*case R.id.btn_attribute:
                        MyCollectionData mData = new MyCollectionData();
                        mData.setName(holder.name);
                        mData.setDescri(holder.description);
                        Intent intent = new Intent(HomeActivity.this, AttributeActivity.class);
                        intent.putExtra("FLAG", "2");
                        intent.putExtra("collectionId", holder.id);
                        intent.putExtra("data", mData);
                        startActivity(intent);
                        Log.i(TAG, "Modify attribute " + holder.nameTv.getText());
                        break;*/
                }
            }
        };
    }

    private int getIconIndex(String id){
        int index = 0;
        for(int x=0;x<all_id.length;x++){
            if(all_id[x].equals(id)){
                index = x;
                return index;
            }
        }
        return index;
    }

    class ViewHolder {
        private String id;
        private TextView idTv;
        private TextView nameTv;
        private TextView desTv;
        //private TextView ctimeTv;
        private TextView ltimeTv;
       // private LinearLayout hide;
        //private ImageButton imageButton;
        private String name;
        private String description;
        private ImageView icon;
        private TextView detect;

        public ViewHolder(View view) {
            //hide = (LinearLayout) view.findViewById(R.id.hide);
            idTv = (TextView) view.findViewById(R.id.collection_id);
            nameTv = (TextView) view.findViewById(R.id.text_name);
            desTv = (TextView) view.findViewById(R.id.text_description);
            //ctimeTv = (TextView) view.findViewById(R.id.text_ctime);
            ltimeTv = (TextView) view.findViewById(R.id.text_ltime);
           // imageButton = (ImageButton) view.findViewById(R.id.imagebutton);
            icon = (ImageView)view.findViewById(R.id.icon);
            detect =(TextView)view.findViewById(R.id.detect);
            view.setTag(this);
        }
    }


    public JSONArray getJsonArray() {
        String path = "/collection/list";
        try {
            Response response = HttpMethods.TGetResponse(path, user_id, token);
            if (response.isSuccessful()) {
                String result = response.body().string();
                Log.e(TAG, "result----->" + result);
                JSONObject jsonObject = new JSONObject(result);
                String code = jsonObject.getString("code");
                Log.e(TAG, "code----->" + code);
                if (code.compareTo("0") == 0) {
                    String jsonobj = jsonObject.getString("jsonObj");
                    jsonArray = new JSONArray(jsonobj);
                    if (jsonArray != null) {
                        CollectionHandler.sendMessage(Message.obtain(CollectionHandler, 0));
                    } else {
                        CollectionHandler.sendMessage(Message.obtain(CollectionHandler, 1));
                    }
                }
            }
            return jsonArray;
        } catch (Exception e) {

        }
        return null;

    }



    private void GetCollection() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                String path = "/collection/list";
                try {
                    Response response = HttpMethods.TGetResponse(path, user_id, token);
                    if (response.isSuccessful()) {
                        String result = response.body().string();
                        Log.e(TAG, "result----->" + result);
                        JSONObject jsonObject = new JSONObject(result);
                        String code = jsonObject.getString("code");
                        Log.e(TAG, "code----->" + code);
                        if (code.compareTo("0") == 0) {
                            String jsonobj = jsonObject.getString("jsonObj");
                            if(yphone.equals(tqphone)){
                                JSONArray mjsonArray = new JSONArray(jsonobj);
                                jsonArray = settq(mjsonArray);
                            }else{
                                //jsonArray = new JSONArray(jsonobj);
                                JSONArray mjsonArray = new JSONArray(jsonobj);
                                jsonArray = setYfz(mjsonArray);
                            }

                            if (jsonArray != null) {

                                CollectionHandler.sendMessage(Message.obtain(CollectionHandler, 0));
                            } else {
                                CollectionHandler.sendMessage(Message.obtain(CollectionHandler, 1));
                            }
                        } else {
                            CollectionHandler.sendMessage(Message.obtain(CollectionHandler, 99));
                        }
                    } else {
                        CollectionHandler.sendMessage(Message.obtain(CollectionHandler, 99));
                        Log.e(TAG, "http not execute");
                    }
                } catch (IOException e) {
                    CollectionHandler.sendMessage(Message.obtain(CollectionHandler, 99));
                    e.printStackTrace();
                } catch (JSONException e) {
                    CollectionHandler.sendMessage(Message.obtain(CollectionHandler, 99));
                    e.printStackTrace();
                }
            }
        }.start();
    }
    private JSONArray settq(JSONArray mjsonArray){
         JSONObject collection = null;
         String id = "0";
        JSONArray tqJsonArray = new JSONArray() ;
        for(int i =0;i<mjsonArray.length();i++){
            try{
                collection = (JSONObject)mjsonArray.get(i);
                id = collection.getString("collectionId");
                if(id.equals("1")||id.equals("38")||id.equals("39")||id.equals("40")||id.equals("41")){
                    tqJsonArray.put(collection);
                }
            }catch (JSONException e) {
                e.printStackTrace();
            }

        }
        return tqJsonArray;
    }

    private JSONArray setYfz(JSONArray mjsonArray){
        JSONObject collection = null;
        String id = "0";
        JSONArray tqJsonArray = new JSONArray() ;
        for(int i =0;i<mjsonArray.length();i++){
            try{
                collection = (JSONObject)mjsonArray.get(i);
                id = collection.getString("collectionId");
                //1,3,4,10,11,40,43,44,46
                if(id.equals("1")||id.equals("3")||id.equals("4")||id.equals("10")||id.equals("11")||id.equals("40")||id.equals("43")||id.equals("44")||id.equals("46")){
                    tqJsonArray.put(collection);
                }
            }catch (JSONException e) {
                e.printStackTrace();
            }

        }
        return tqJsonArray;
    }

    private void modifyCollectionInfo(final String json) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String path = "/collection/modifyNameAndDesc";
                try {
                    Response response = HttpMethods.NewResponse(path, user_id, token, json);
                    if (response.isSuccessful()) {
                        String result = response.body().string();
                        Log.e(TAG, "result----->" + result);
                        JSONObject jsonObject = new JSONObject(result);
                        String code = jsonObject.getString("code");
                        Log.e(TAG, "code----->" + code);
                        if (code.compareTo("0") == 0) {
                            jsonArray = getJsonArray();
                            CollectionHandler.sendMessage(Message.obtain(CollectionHandler, 2));
                        } else {
                            CollectionHandler.sendMessage(Message.obtain(CollectionHandler, 3));
                        }
                    } else {
                        CollectionHandler.sendMessage(Message.obtain(CollectionHandler, 99));
                        Log.e(TAG, "response fail...");
                    }
                } catch (IOException e) {
                    CollectionHandler.sendMessage(Message.obtain(CollectionHandler, 99));
                    e.printStackTrace();
                } catch (JSONException e) {
                    CollectionHandler.sendMessage(Message.obtain(CollectionHandler, 99));
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /*private  void modifyAttributes(final String json) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String path = "/collection/modifyAttributes";
                try {
                    Response response = HttpMethods.NewResponse(path, user_id, token, json);
                    if(response.isSuccessful()) {
                        String result = response.body().string();
                        Log.e(TAG,"result----->" + result);
                    } else {
                        Log.e(TAG,"response fail...");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }*/
}
